package com.okbihuo.perm.core.auth.handler;

import cn.hutool.extra.servlet.ServletUtil;
import com.okbihuo.perm.core.auth.helper.AuthHelper;
import com.okbihuo.perm.core.logger.publisher.LogPublisher;
import com.okbihuo.perm.core.tool.api.R;
import com.okbihuo.perm.core.tool.api.ResultCode;
import com.okbihuo.perm.core.tool.jackson.JsonUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        R<Object> fail = R.fail(ResultCode.REQ_REJECT, "需要权限才能访问该内容");
        LogPublisher.info("需要权限才能访问该内容", AuthHelper.currentAwareUserId());
        ServletUtil.write(httpServletResponse, JsonUtil.toJson(fail), "application/json;charset=UTF-8");
    }
}
